package com.dayuan.service;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dayuan.bean.Goods;
import com.dayuan.bean.Order;
import com.dayuan.bean.OrderDetails;
import com.dayuan.bean.Stock;
import com.dayuan.constant.AjaxMsg;
import com.dayuan.dao.OrderMapper;
import com.dayuanit.pay.domain.PayOrder;
import com.dayuanit.pay.service.PayService;

@Service
public class OrderService {

	@Resource
	private OrderMapper orderMapper;

	@Resource
	private StockService stockService;
	@Resource
	private GoodsService goodsService;
	
	@Resource
	private PayService payService;

	/* 生成订单主表 */
	public int insertOrder(Order order) {
		return orderMapper.insertOrder(order);
	}

	/* 生成订单详表 */
	public int insertorderDetails(OrderDetails orderDetails) {
		return orderMapper.insertorderDetails(orderDetails);
	}

	/*下订单*/
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String order(Integer goodsId, Integer Number, Integer id) {
		try {
			// 查询库存并且for update
			Stock stock = stockService.selectStock(goodsId);
			if (stock.getNumber().intValue() < Number.intValue()) {
				return AjaxMsg.PAY_FAIL.getPay();
			}

			// 减库存
			Stock stock1 = new Stock();
			stock1.setGoods_id(goodsId);
			stock1.setNumber(Number);
			stockService.updateStock(stock1);

			//查询商品价格
			Goods goods = goodsService.selectGoodsAllById(goodsId);
			
			// insert订单主表
			Order or = new Order();
			or.setMoney(goods.getPromotion_price() * Number);
			or.setUser_id(id);
			insertOrder(or);
			int temp = or.getId();

			// insert订单详表
			OrderDetails ord = new OrderDetails();
			ord.setGoods_id(goodsId);
			ord.setOrder_id(temp);
			ord.setPrice(goods.getPromotion_price());
			ord.setNumber(Number);
			insertorderDetails(ord);
			
			//支付系统
			PayOrder payOrder = new PayOrder();
			payOrder.setPayChannel(4);
			payOrder.setAmount(String.valueOf(or.getMoney()));
			payOrder.setBizId(String.valueOf(or.getId()));
			payOrder.setUserId(id);
			payOrder.setDetailMsg("若爆了");
			
			Map<String, Object> result = payService.addPayOrder(payOrder);
			//支付系统成功还是失败
			if(Boolean.parseBoolean(result.get("success").toString())==false){
				
				return  AjaxMsg.PAY_FAIL.getPay();
			}
			
		/*	System.out.println(result.get("payOrderUrl").toString());*/
			return result.get("payOrderUrl").toString();
			
			
			
		} catch (Exception e) {
			throw e;
		}
		
	}

	
	 /*修改订单状态*/  
	public void updateOrderState(Integer state,Integer id){
		orderMapper.updateOrderState(state, id);
	}
	
}
